package com.enjoy.xbase.xui.adapter;

import android.util.SparseArray;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.IdRes;
import androidx.annotation.NonNull;
import androidx.recyclerview.widget.RecyclerView;


public class BaseRvViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
    private BaseRvAdapter adapter;
    private SparseArray<View> views = new SparseArray<>();

    public BaseRvViewHolder(@NonNull View itemView, BaseRvAdapter adapter) {
        super(itemView);
        this.adapter=adapter;
        initItemClick();
    }
    private void initItemClick(){
        if (adapter.getOnItemClickListener() != null) {
            itemView.setOnClickListener(v ->  {
                int position = getAdapterPosition();
                adapter.getOnItemClickListener().onItemClick(adapter, itemView, position);
            });
        }
    }


    public final <T extends View> T findViewById(@IdRes int id) {
        View view = views.get(id);
        if (view == null) {
            view = itemView.findViewById(id);
            if (view != null) {
                views.put(id, view);
            }
        }
        return (T) view;
    }

    public void setText(int id, CharSequence text) {
        TextView tv = findViewById(id);
        tv.setText(text);
    }
    /**
     * 描述：设置点击事件
     *
     * @param ids
     */
    public void setOnClick(@IdRes int... ids) {
        for (int id : ids) {
            View view = findViewById(id);
            view.setOnClickListener(this);
        }
    }
    @Override
    public void onClick(View v) {
        if (adapter.getOnItemChildClickListener() != null) {
            int position = getAdapterPosition();
            if (position>-1){
                adapter.getOnItemChildClickListener().onItemChildClick(adapter, v, position);
            }
        }
    }
}
